<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header" style="border-bottom: 1px solid #e4e7ed;padding-bottom: 10px;">
          <div class="title-container">
            <el-icon style="font-size: 24px;">
              <Handbag />
            </el-icon>
            <h2>库存监控</h2>
          </div>
          <div class="button-container">
            <el-button type="primary" @click="drawer = true"><el-icon>
                <Edit />
              </el-icon>库存物品调整</el-button>
            <el-button type="primary" @click="drawer2 = true"><el-icon>
                <Notebook />
              </el-icon>库存盘点</el-button>
          </div>
        </div>
        <!-- 搜索 -->
        <el-card style="margin-top: 15px;border-radius: 10px;">
          <div class="search-container">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="食材">
                <el-select v-model="searchForm.goods" placeholder="商品食材" class="search-select">
                  <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.goods_id"
                    style="padding-left: 10px;" />
                </el-select>
              </el-form-item>
              <el-form-item label="仓库">
                <el-select v-model="searchForm.warehouse" placeholder="仓库" class="search-select">
                  <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.house_id"
                    style="padding-left: 10px;" />
                </el-select>
              </el-form-item>
              <el-form-item label="库存状态">
                <el-select v-model="searchForm.status" placeholder="状态" class="search-select">
                  <el-option label="正常" value="0" />
                  <el-option label="废弃" value="1" />

                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="delhandleSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

      </template>

      <el-table :data="tableData" style="width: 100%">

        <el-table-column label="ID" width="80">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span>{{ scope.row.stock_id }}</span>
            </div>
          </template>
        </el-table-column>


        <el-table-column label="食材编号" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.goods_code }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="食材名称" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.goods_name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单位" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.unit }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="规格" width="150">
          <template #default="scope">
            <div>
              <span>{{ scope.row.specification }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="仓库" width="110">
          <template #default="scope">
            <div>
              <span>{{ scope.row.house_name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="当前库存" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.current_stock }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="安全库存" width="100">
          <template #default="scope">
            <div>
              <span>{{ scope.row.safety_stock * 1 }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>当前库存: {{ scope.row.current_stock }}</div>
                <div v-if="scope.row.current_stock < scope.row.safety_stock * 0.5">状态: {{ getStatusText(0) }}</div>
                <div v-else-if="scope.row.current_stock > scope.row.safety_stock * 1.5">状态: {{ getStatusText(2) }}</div>
                <div v-else>状态: {{ getStatusText(1) }}</div>
              </template>
              <template #reference>
                <el-tag :type="getStatusType(0)" v-if="scope.row.current_stock < scope.row.safety_stock * 0.5">
                  {{ getStatusText(0) }}
                </el-tag>
                <el-tag :type="getStatusType(2)" v-else-if="scope.row.current_stock > scope.row.safety_stock * 1.5">
                  {{ getStatusText(2) }}
                </el-tag>
                <el-tag :type="getStatusType(1)" v-else>
                  {{ getStatusText(1) }}
                </el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <!-- 把最近入库日期格式化为yyyy-MM-dd HH:mm:ss -->
        <el-table-column label="最近入库日期" width="200">
          <template #default="scope">
            <div>
              <span>{{ scope.row.updated_at ? new Date(scope.row.updated_at).toLocaleString() : '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 把保质期格式化为yyyy-MM-dd -->
        <el-table-column label="保质期" width="200">
          <template #default="scope">
            <div>
              <span>{{ scope.row.latest_expiration_date ? new
                Date(scope.row.latest_expiration_date).toLocaleDateString() : '-' }}</span>
            </div>
          </template>
        </el-table-column>


        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.$index, scope.row)">
              <el-icon style="margin-right: 5px;">
                <View />
              </el-icon>查看
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 15, 20, 30]"
          :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

    </el-card>
    <!-- 库存物品调整抽屉组件 -->
    <el-drawer v-model="drawer" :direction="direction" size="50%">
      <template #header>
        <h4>库存物品调整</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <div class="drawer-content-title">
            <h4>调整信息</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="updateForm" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list">
                <li>
                  <p>食材名称</p>
                  <el-select v-model="updateForm.goods_name" placeholder="食材名称" @change="handleGoodsChange">
                    <el-option :label="item.name" :value="item.cate_id" v-for="item in goodsList"
                      style="padding-left: 5px;" />
                  </el-select>
                </li>

                <li>
                  <p>仓库</p>
                  <el-select v-model="updateForm.warehouse" placeholder="仓库" @change="getAreaList">
                    <el-option v-for="item in warehouseList" :label="item.name" :value="item.house_id" />
                  </el-select>
                </li>

                <li>
                  <p>仓库区域</p>
                  <el-select v-model="updateForm.area_id" placeholder="仓库区域" @change="getStockList">
                    <el-option v-for="item in areaList" :label="item.area_name" :value="item.area_id" />
                  </el-select>
                </li>
                <li>
                  <p>规格型号</p>
                  <el-input v-model="updateForm.Specifications" />
                </li>
                <li>
                  <p>单位</p>
                  <el-input v-model="updateForm.unit" />
                </li>
                <li>
                  <p>当前库存</p>
                  <el-input v-model="updateForm.inventory" />
                </li>
                <li>
                  <p>调整数量</p>
                  <el-input-number v-model="updateForm.adjustment" :precision="2" :step="1.0" size="small" />
                  <!-- <el-input v-model="updateForm.adjustment" /> -->
                </li>
                <li>
                  <p>调整类型</p>
                  <el-select v-model="updateForm.adjustmentType" placeholder="调整类型">
                    <el-option label="采购入库" value="purchase_in" />
                    <el-option label="出库" value="outbound" />
                    <el-option label="调整" value="adjust" />
                    <el-option label="盘点" value="check" />
                  </el-select>
                </li>
                <li>
                  <p>调整原因</p>
                  <el-select v-model="updateForm.reason" placeholder="调整原因">
                    <el-option label="入库" value="1" />
                    <el-option label="出库" value="2" />
                    <el-option label="损耗" value="3" />
                    <el-option label="损坏" value="4" />
                    <el-option label="其他" value="5" />
                  </el-select>
                </li>
                <li style="display: block;">
                  <p>备注</p>
                  <el-input v-model="updateForm.notes" type="textarea" :rows="4" style="width:900px" />
                </li>

              </ul>
            </el-form>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick"> 取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
        </div>
      </template>
    </el-drawer>




    <!-- 查看明细 -->
    <el-drawer v-model="drawer3" :direction="direction" size="50%">
      <template #header>
        <h4>查看库存明细-{{ lookForm.goods_code }}</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <div class="drawer-content-title">
            <h4>库存明细</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="lookForm" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list-lock">
                <li>
                  <p>食材编号</p>
                  <el-input v-model="lookForm.goods_code" />
                </li>
                <li>
                  <p>食材名称</p>
                  <el-input v-model="lookForm.goods_name" />
                </li>
                <li>
                  <p>规格型号</p>
                  <el-input v-model="lookForm.specification" />
                </li>
                <li>
                  <p>单位</p>
                  <el-input v-model="lookForm.unit" />
                </li>
                <li>
                  <p>仓库名称</p>
                  <el-input v-model="lookForm.house_id" />
                </li>
                <li>
                  <p>库存状态</p>
                  <el-input v-if="lookForm.current_stock < lookForm.safety_stock * 0.5" value="低于安全储量" />
                  <el-input v-else-if="lookForm.current_stock > lookForm.safety_stock * 1.5" value="超出安全储量" />
                  <el-input v-else value="处于正常储量" />
                </li>
                <li>
                  <p>当前库存</p>
                  <el-input v-model="lookForm.current_stock" />
                </li>
                <li>
                  <p>安全库存</p>
                  <el-input v-model="lookForm.safety_stock" />
                </li>
                <li>
                  <p>最近入库日期</p>
                  <!-- <div class="block"> -->
                  <el-date-picker v-model="lookForm.updated_at" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" style="width: 100%" />
                  <!-- </div> -->
                </li>
                <li>
                  <p>保质期</p>
                  <!-- <div class="block"> -->
                  <el-date-picker v-model="lookForm.latest_expiration_date" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" style="width: 100%" />
                  <!-- </div> -->
                </li>
              </ul>


            </el-form>
            <el-table :data="inventoryDetailForm" border style="width: 100%">
              <el-table-column prop="log_id" label="序号" width="80" />
              <el-table-column prop="change_time" label="变动日期" width="180">
                <template #default="scope">
                  <span>{{ scope.row.change_time ? new Date(scope.row.change_time).toLocaleString() : '-' }}</span>
                </template>
              </el-table-column>>

              <el-table-column prop="change_type" label="变动类型" width="110" >
                <template #default="scope">
                  <span>{{ scope.row.change_type === 'purchase_in' ? '入库' : (scope.row.change_type === 'outbound' ? '出库' : (scope.row.change_type === 'adjust' ? '调整' : (scope.row.change_type === 'check' ? '盘点' : '其他'))) }}</span>
                   <!-- 变动类型：purchase_in(入库), outbound(出库), adjust(调整), check(盘点) -->
                </template>
              </el-table-column>

              <el-table-column prop="change_quantity" label="变动数量" width="90" />
              <el-table-column label="操作人" width="120">
                <template #default="scope">
                  <div>
                    <span>{{ getUserNameById(scope.row.user_id) || scope.row.user_id || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="related_order" label="关联单据" width="155" />
              <el-table-column prop="notes" label="备注" width="200" />
            </el-table>
          </div>
        </div>
      </template>

    </el-drawer>



    <!-- 库存盘点抽屉组件 -->
    <el-drawer v-model="drawer2" :direction="direction" size="50%">
      <template #header>
        <h4>库存盘点</h4>
      </template>
      <template #default>
        <div class="drawer-content">
          <!-- 具体内容 -->
          <div class="drawer-content-title">
            <h4>盘点信息</h4>
          </div>
          <div class="drawer-content-form">
            <el-form :model="addFormDate" :rules="rules" ref="formRef" label-width="80px"
              style="display: flex; justify-content: space-between;">
              <ul class="form-list">
                <!-- <li> -->
                <!-- <p>盘点日期</p> -->
                <!-- <div class="block"> -->
                <!-- <el-date-picker v-model="inventoryDate" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" style="width: 100%" /> -->
                <!-- </div> -->
                <!-- </li> -->
                <li>
                  <p>仓库</p>
                  <el-select v-model="addFormDate.warehouse" placeholder="仓库" @change="getAreaList">
                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.house_id"
                      style="padding-left: 10px;" />
                  </el-select>
                </li>
                <li>
                  <p>仓库区域</p>
                  <el-select v-model="addFormDate.area_id" placeholder="仓库区域">
                    <el-option v-for="item in areaList" :label="item.area_name" :value="item.area_id"
                      style="padding-left: 10px;" />
                  </el-select>
                </li>
                <li></li>
                <li>
                  <p>备注</p>
                  <el-input v-model="addFormDate.remark" type="textarea" :rows="4" style="width:900px" />
                </li>
              </ul>
            </el-form>
          </div>
          <div class="drawer-content-title">
            <h4>盘点明细</h4>
            <el-button type="primary" @click="addInventoryRow"><el-icon>
                <Plus />
              </el-icon>添加行</el-button>
          </div>
          <!-- 盘点明细表格 -->
          <div class="inventory-detail-table">
            <table class="detail-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>食材名称</th>
                  <th>规格型号</th>
                  <th>单位</th>
                  <th>系统库存</th>
                  <th>实际库存</th>
                  <th>差异数量</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in inventoryDetails" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>
                    <el-select v-model="item.foodName" placeholder="请选择食材" @change="(val) => onFoodChange(val, index)">
                      <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.goods_id"
                        style="padding-left: 10px;" />
                    </el-select>
                  </td>
                  <td>{{ item.spec }}</td>
                  <td>{{ item.unit }}</td>
                  <td>{{ item.systemStock }}</td>

                  <td>
                    <el-input-number v-model="item.actualStock" :min="0" @change="() => calculateDiff(index)" />
                  </td>
                  <td :class="{ negative: item.diff !== null && item.diff < 0 }">{{ item.diff }}</td>
                  <td>
                    <el-input v-model="item.remark" placeholder="请输入备注信息" />
                  </td>
                  <td>
                    <el-button type="danger" :icon="Delete" size="small" @click="deleteInventoryRow(index)"></el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick"> 取消</el-button>
          <el-button type="primary" @click="confirmClick"> 确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Timer, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import inventoryApi from '../../api/inventory'
import inventoryinApi from '../../api/inventoryin'
import { useInventoryStore } from '../../stores/inventory'
import { id } from 'element-plus/es/locales.mjs'
// import { watch } from 'less'




const drawer = ref(false)
const drawer2 = ref(false)
const drawer3 = ref(false)
const direction = ref('rtl')

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)

const addFormDate = ref({
  warehouse: '',
  area_id: '',
  remark: '',
})

// 库存物品调整列表
let updateForm = ref({
  goods_name: '',
  warehouse: '',
  area_id: '',
  inventory: '',
  adjustment: '',
  Specifications: '',
  unit: '',
  adjustmentType: '',
  notes: '',
  related_order: '',
})


let searchForm = ref({
  goods: null,
  warehouse: null,
  status: null
})
let lookForm = ref({
  goods_code: "",
  goods_name: "",
  specification: "",
  unit: "",
  house_id: '',
  current_stock: '',
  safety_stock: '',
  updated_at: '',
  latest_expiration_date: ''
})

// 查看明细数据
let inventoryDetailForm = ref([])
const kuguanList = ref([])

// 根据user_id查找用户名
const getUserNameById = (user_id) => {
  if (!user_id || !kuguanList.value.length) return ''
  const user = kuguanList.value.find(item => item.user_id === user_id || item.id === user_id)
  return user?.user_name || user?.name || ''
}
// 查看商品明细
const handleViewDetail = async (index, row) => {
  console.log(index, row,)
  drawer3.value = true
  lookForm.value = row
  const kuguan = await inventoryinApi.getUserList({
    page: 1,
    pageSize: 1000
  })
  console.log('仓库主管API返回数据:', kuguan)
  console.log('仓库主管数据结构:', kuguan.data)
  kuguanList.value = kuguan.data || []
  // 初始化库存明细数据
  const res = await inventoryApi.getInventoryDetail({
    stock_id: row.goods_id
  })

  if (res.code === 0) {
    inventoryDetailForm.value = res.data
  } else {
    ElMessage.error(res.msg || '获取库存明细失败')
    return null
  }

}
const handleDelete = (index, row) => {
  console.log(index, row)
}

// 库存列表数据
const tableData = ref([])

// 食材列表数据
const goodsList = ref([])
// 物品调整后的数据
const updateinventory = ref([])
// 仓库列表数据
const warehouseList = ref([])
// 仓库区域列表数据
const areaList = ref([])
// 库存id
const stock_id = ref(null)
// 仓库区域id
const area_id = ref(null)
// 总条数
const total = ref(0)

const inventoryStore = useInventoryStore()

// 获取库存数据
async function getInventoryList() {
  try {
    // 只在参数有实际值时才传递，避免空值过滤
    const params = {
      page: currentPage4.value,
      pageSize: pageSize4.value
    }

    // 只有当goods_id有值时才添加（不等于null和空字符串）
    if (searchForm.value.goods !== null && searchForm.value.goods !== '') {
      params.goods_id = searchForm.value.goods
    }

    // 只有当house_id有值时才添加
    if (searchForm.value.warehouse !== null && searchForm.value.warehouse !== '') {
      params.house_id = searchForm.value.warehouse
    }

    // 只有当status是有效数字时才添加（避免默认0值被过滤）
    if (searchForm.value.status !== undefined && searchForm.value.status !== null && searchForm.value.status !== '') {
      params.status = searchForm.value.status
    }

    console.log('请求参数:', params)
    const res = await inventoryApi.getInventory(params)
    console.log(res.data, "库存列表")
    if (res.code === 0) {
      // 检查返回的数据结构

      // 存储库存列表到 Pinia 状态管理
      tableData.value = res.data.list
      // 存储总条数到 Pinia 状态管理
      total.value = res.data.total
      inventoryStore.inventoryList = res.data.list
    } else {
      ElMessage.error(res.msg || '获取库存列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取库存列表失败')
  }
}
getInventoryList()

// 每页条数
const handleSizeChange = (val) => {
  pageSize4.value = val
  getInventoryList()
  console.log(`${val} items per page`)
}
// 页码
const handleCurrentChange = (val) => {

  currentPage4.value = val
  getInventoryList()
  console.log(`current page: ${val}`)
}

const gid = ref(null)
// 当商品选择改变时，重置仓库选择
const handleGoodsChange = async (val) => {
  console.log('选择的商品ID:', val)
  gid.value = val
  const res = await inventoryApi.getInventoryDetail({
    stock_id: val
  })
  // // 只取最新的那一条那一条
  if (res.code === 0 && res.data && res.data.length) {
    const maxIndex = res.data.length - 1
    updateinventory.value = [res.data[maxIndex]]
  } else {
    updateinventory.value = []
  }
  console.log(updateinventory.value[0])
  // updateForm.value = {...updateinventory.value[0]}
  // updateForm.value.warehouse = updateinventory.value[0].house_id

  if (updateinventory.value[0]?.house_id) {
    const cangku = await inventoryApi.getHouseInfo({
      house_id: updateinventory.value[0].house_id
    })
    console.log(cangku.data[0])
    updateForm.value.warehouse = cangku.data[0]?.house_id || ''
    // updateForm.warehouse.value=cangku.data[0].house_id
    const goods = await inventoryApi.getInventoryByGoodsId({
      goods_id: val
    })
    console.log(goods.data.mergedResult, '库存信息')
    stock_id.value = goods.data.mergedResult.stock_id
    updateForm.value.Specifications = goods.data.mergedResult.specification;
    updateForm.value.unit = goods.data.mergedResult.unit;
    updateForm.value.inventory = goods.data.mergedResult.current_stock;
    // console.log(goods.data.mergedResult)
  }

}

// 监听仓库变化，重新拉取区域列表
watch(() => updateForm.value.warehouse, async (newVal, oldVal) => {
  // 仅在值真正改变且不为空时触发
  if (newVal !== oldVal && newVal) {
    await getAreaList()
  }
})

// 根据当前选中的仓库拉取区域列表
const getAreaList = async () => {
  // 若未选中仓库，直接清空区域列表
  if (!updateForm.value.warehouse) {
    areaList.value = []
    inventoryStore.areaList = []
    return
  }

  try {
    const res = await inventoryApi.getAreaInfo({
      page: 1,
      pageSize: 1000,
      house_id: updateForm.value.warehouse
    })
    console.log(res.data, "仓库区域列表")
    if (res.code === 0) {
      // 兼容后端可能返回的 data / list 字段，取全部数据而非第一条
      const list = res.data
      areaList.value = list
      inventoryStore.areaList = list

    } else {
      ElMessage.error(res.msg || '获取仓库区域列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取仓库区域列表失败')
  }
}





async function getGoodsList() {
  try {
    const res = await inventoryApi.getGoods({
      page: 1,
      pageSize: 1000
    })
    console.log(res.data, "搜索框的食材id")
    if (res.code === 0) {
      goodsList.value = res.data.data
      inventoryStore.goodsList = res.data.list
    } else {
      ElMessage.error(res.msg || '获取商品列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取商品列表失败')
  }
}
getGoodsList()

// 获取仓库列表
async function getWarehouseList() {
  try {
    const res = await inventoryApi.getWarehouse({
      page: 1,
      pageSize: 1000
    })
    console.log(res.data, "搜索框的仓库id")
    if (res.code === 0) {
      // 检查数据字段名称，可能是data或list
      if (res.data.data) {
        warehouseList.value = res.data.data
        inventoryStore.warehouseList = res.data.data
      } else if (res.data.list) {
        warehouseList.value = res.data.list
        inventoryStore.warehouseList = res.data.list
      }
      // 添加日志检查返回的数据结构
      console.log('仓库数据字段:', Object.keys(res.data.data?.[0] || res.data.list?.[0] || {}))
    } else {
      ElMessage.error(res.msg || '获取仓库列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取仓库列表失败')
  }
}
getWarehouseList()
// 仓库区域列表
const getStockList = (val) => {
  console.log(val, "仓库区域id")
  area_id.value = val
}

const user_id = ref(null)
onMounted(() => {
  // 读取本地存储的某个键的值，替换为实际的 key（如 'role_id'、'inventory' 等）
  user_id.value = localStorage.getItem('user_id');
  console.log('获取到的存储数据：', user_id.value); // 此处即可拿到对应的值“1”
});


// 编辑库存信息提交
const handleSubmit = async () => {
  // console.log( gid.value,updateForm.value.inventory + updateForm.value.adjustment)
  try {
    const res = await inventoryApi.putInventoryInfo({
      goods_id: gid.value,
      house_id: updateForm.value.warehouse,
      current_stock: Number(updateForm.value.inventory) + Number(updateForm.value.adjustment),
      notes: updateForm.value.notes || '暂无'
    })
    if (res.code === 0) {
      ElMessage.success('更新成功')
      // 添加库存记录
      await inventoryStore.addInventoryLog({
        stock_id: stock_id.value,
        goods_id: gid.value,
        house_id: updateForm.value.warehouse,
        area_id: area_id.value,
        change_type: updateForm.value.adjustmentType,
        change_reason: updateForm.value.reason,
        change_quantity: updateForm.value.adjustment,
        balance: Number(updateForm.value.inventory) + Number(updateForm.value.adjustment),
        related_order: updateForm.value.relatedOrder || '暂无',
        user_id: user_id.value,
        notes: updateForm.value.notes || '暂无'
      })
      // 刷新当前页面数据
      getInventoryList()
      // 关闭弹窗
      drawer.value = false
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '更新失败')
  }
}




async function getAreaInfo() {
  try {
    const res = await inventoryApi.getArea({
      page: 1,
      pageSize: 1000
    })
    console.log(res.data, "搜索框的仓库区域id")
    if (res.code === 0) {
      // 检查数据字段名称，可能是data或list
      if (res.data.data) {
        areaList.value = res.data.data
        inventoryStore.areaList = res.data.data
      } else if (res.data.list) {
        areaList.value = res.data.list
        inventoryStore.areaList = res.data.list
      }
      // 添加日志检查返回的数据结构
      console.log('仓库区域数据字段:', Object.keys(res.data.data?.[0] || res.data.list?.[0] || {}))
    } else {
      ElMessage.error(res.msg || '获取仓库区域列表失败')
      return null
    }
  } catch (error) {
    ElMessage.error(error.message || '获取仓库区域列表失败')
  }
}




const handleSearch = () => {
  // 搜索时重置页码为1
  currentPage4.value = 1
  // 调用获取库存列表函数，我们已经修改了它只传递非空参数
  getInventoryList()
}

const delhandleSearch = () => {
  searchForm.value = {
    goods: null,
    warehouse: null,
    status: null
  }
  // 重置后也重置页码并重新获取数据
  currentPage4.value = 1
  getInventoryList()
}



// 盘点明细数据
const inventoryDetails = ref([
  {
    foodName: null,
    spec: null,
    unit: null,
    systemStock: null,
    actualStock: null,
    diff: null,
    remark: null
  }
])

const getStatusText = (status) => {
  switch (status) {
    case 0: return '低于安全库存';
    case 1: return '处于正常储量';
    case 2: return '超过正常储量';
  }
};

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning';  // 已作废-警告色
    case 1: return 'success';     // 待收货-信息色
    case 2: return 'primary';  // 收货中-主要色
  }
};

const radio1 = ref('Option 1')


function cancelClick() {
  drawer2.value = false
}
// 添加盘点行
function addInventoryRow() {
  inventoryDetails.value.push({
    foodName: '',
    spec: '',
    unit: '',
    systemStock: 0,
    actualStock: null,
    diff: null,
    remark: ''
  })
}
// 




// 删除盘点行
function deleteInventoryRow(index) {
  inventoryDetails.value.splice(index, 1)
}

const inventoryDate = ref(null)


const add_id = ref(null)
// 选择食材时自动填充规格、单位和系统库存
const goodsInfo = ref(null)
async function onFoodChange(val, rowIndex = 0) {
  console.log(`选择食材 - 行索引: ${rowIndex}, 食材ID: ${val}`)
  add_id.value = val
  try {
    // 获取商品库存信息
    const goods = await inventoryApi.getInventoryByGoodsId({
      goods_id: val
    })

    if (goods.data && goods.data.mergedResult) {
      const goodsData = goods.data.mergedResult
      console.log('商品信息:', goodsData)

      // 直接更新指定行的数据，保持响应式
      if (inventoryDetails.value[rowIndex]) {
        // 使用 Object.assign 或直接赋值属性来保持响应式
        inventoryDetails.value[rowIndex].spec = goodsData.specification || ''
        inventoryDetails.value[rowIndex].unit = goodsData.unit || ''
        inventoryDetails.value[rowIndex].systemStock = goodsData.current_stock || 0

        // 重新计算差异
        if (inventoryDetails.value[rowIndex].actualStock !== null &&
          inventoryDetails.value[rowIndex].actualStock !== undefined) {
          inventoryDetails.value[rowIndex].diff =
            inventoryDetails.value[rowIndex].actualStock - (goodsData.current_stock || 0)
        }

        // 保存商品信息供其他地方使用
        goodsInfo.value = goodsData

        console.log(`第${rowIndex + 1}行数据已更新:`, inventoryDetails.value[rowIndex])
      }

      // 获取仓库信息（如果需要更新表单）
      if (goodsData.house_id) {
        try {
          const cangku = await inventoryApi.getHouseInfo({
            house_id: goodsData.house_id
          })

          if (updateForm.value && cangku.data && cangku.data[0]) {
            updateForm.value.warehouse = cangku.data[0]?.house_id || ''
          }
        } catch (error) {
          console.warn('获取仓库信息失败:', error)
        }
      }
    } else {
      // 如果没有获取到商品信息，清空相关字段
      if (inventoryDetails.value[rowIndex]) {
        inventoryDetails.value[rowIndex].spec = ''
        inventoryDetails.value[rowIndex].unit = ''
        inventoryDetails.value[rowIndex].systemStock = 0
        inventoryDetails.value[rowIndex].diff = null
      }
      goodsInfo.value = null
    }
  } catch (error) {
    console.error('获取食材信息失败:', error)
    ElMessage.error('获取食材信息失败，请重试')

    // 出错时清空相关字段
    if (inventoryDetails.value[rowIndex]) {
      inventoryDetails.value[rowIndex].spec = ''
      inventoryDetails.value[rowIndex].unit = ''
      inventoryDetails.value[rowIndex].systemStock = 0
      inventoryDetails.value[rowIndex].diff = null
    }
  }
}
// 计算差异 - 支持多行盘点
const calculateDiff = (rowIndex = null) => {
  if (rowIndex !== null) {
    // 计算指定行的差异
    const item = inventoryDetails.value[rowIndex]
    if (item && item.actualStock !== null && item.actualStock !== undefined) {
      item.diff = item.actualStock - (item.systemStock || 0)
      console.log(`第${rowIndex + 1}行差异计算: 实际库存${item.actualStock} - 系统库存${item.systemStock || 0} = ${item.diff}`)
    }
  } else {
    // 计算所有行的差异
    inventoryDetails.value.forEach((item, index) => {
      if (item.actualStock !== null && item.actualStock !== undefined) {
        item.diff = item.actualStock - (item.systemStock || 0)
        console.log(`第${index + 1}行差异计算: 实际库存${item.actualStock} - 系统库存${item.systemStock || 0} = ${item.diff}`)
      }
    })
  }
}

function confirmClick() {
  // 检查是否所有必填项都已填写
  const hasEmptyItem = inventoryDetails.value.some(item =>
    !item.foodName || item.actualStock === null || item.actualStock === undefined
  )

  if (hasEmptyItem) {
    ElMessageBox.alert('请填写完整的盘点信息', '提示', {
      confirmButtonText: '确定'
    })
    return
  }

  ElMessageBox.confirm('确定要提交盘点数据吗？')
    .then(async () => {
      try {
        console.log('提交的盘点数据:', inventoryDetails.value)

        // 遍历所有盘点行，逐条提交
        for (let i = 0; i < inventoryDetails.value.length; i++) {
          const item = inventoryDetails.value[i]

          // 提交每一条盘点数据到后端
          const res = await inventoryStore.addInventory({
            goods_id: item.foodName, // 使用第445行表格中选择的食材ID
            house_id: goodsInfo.value?.house_id || addFormDate.value.warehouse, // 使用商品信息中的仓库ID或表单选择的仓库
            current_stock: item.actualStock, // 使用第445行表格中"实际库存"作为当前库存
            notes: item.remark || '', // 使用第445行表格中每行的备注
          })

          if (res) {
            console.log(`第${i + 1}行盘点数据提交成功`)
          } else {
            console.error(`第${i + 1}行盘点数据提交失败`)
            ElMessage.error(`第${i + 1}行盘点数据提交失败`)
            return // 如果某一行提交失败，停止后续提交
          }
        }

        ElMessage.success('盘点数据全部提交成功')
        // 刷新列表
        getInventoryList()
        // 关闭弹窗
        drawer2.value = false

        // 重置盘点明细数据
        inventoryDetails.value = [
          {
            foodName: null,
            spec: null,
            unit: null,
            systemStock: null,
            actualStock: null,
            diff: null,
            remark: null
          }
        ]

      } catch (error) {
        console.error('盘点数据提交失败:', error)
        ElMessage.error('盘点数据提交失败，请重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}


</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  list-style: none;
}

.app-container {
  // background-color: #fff;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-container {
      width: 120px;
      justify-content: space-evenly;
      display: flex;
      align-items: center;
    }

    .button-container {
      width: 240px;
      justify-content: space-between;
      display: flex;
      align-items: center;

    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.box-card {
  border-radius: 10px;
}

.demo-pagination-block,
.demo-pagination-block {
  margin-top: 20px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 减小抽屉组件header的高度 */
:deep(.el-drawer__header) {
  // padding: 10px 20px;
  // padding: -20 20px;
  margin-bottom: 0px;
  height: auto;
}

:deep(.el-drawer__header h4) {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
}


.drawer-content-title {
  border-bottom: 1px solid #000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;

  h4 {
    color: #1b82f1;
  }
}

:deep(.el-form-item--label-right .el-form-item__label) {
  justify-content: flex-start;
  text-align: right;
}

:deep(.el-button) {
  padding: 8px 16px;
}

.form-list {
  margin: 20px 0;
  width: 100%;
  display: flex;
  // flex-direction: column;
  justify-content: space-between;
  flex-wrap: wrap;

  li {
    width: 32%;
    margin: 10px 0;

    p {
      margin-bottom: 5px;
    }
  }
}

// 盘点明细表格样式
.inventory-detail-table {
  margin-top: 20px;
  width: 100%;
  overflow-x: auto;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;

  th,
  td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #e4e7ed;
    border-right: 1px solid #e4e7ed;
  }

  th {
    background-color: #f5f7fa;
    font-weight: 600;
    color: #606266;
  }

  tr:last-child td {
    border-bottom: none;
  }

  td:last-child,
  th:last-child {
    border-right: none;
    text-align: center;
  }
}

// 调整表格中的输入框样式
.detail-table .el-input,
.detail-table .el-select,
.detail-table .el-input-number {
  width: 120px;
}

// 差异数量为负数时显示红色
.detail-table tbody td:nth-child(7) {
  color: #67c23a; // 默认绿色

  &.negative {
    color: #f56c6c; // 负数红色
  }
}

.search-select {
  width: 320px;
}

.form-list-lock {
  margin: 20px 0;
  width: 100%;
  display: flex;
  // flex-direction: column;
  justify-content: space-between;
  flex-wrap: wrap;

  li {
    width: 48%;
    margin: 10px 0;

    p {
      margin-bottom: 5px;
    }
  }
}
</style>